﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MonoTouchAutoBind
{
    class BindEnum : MonotouchBindContainer
    {

        private string patternStart = @"typedef\s+enum\s*{";
        private string patternEnd = @"}\s*(?'enumName'\w+)\s*;";

        private System.Text.RegularExpressions.Regex regexStart = null;
        private System.Text.RegularExpressions.Regex regexEnd = null;
        private string enumName;

        private string stringCache = "";
        private List<string> enumValues;
        

        public override List<MonotouchBind> bindEngine
        {
            get
            {
                List<MonotouchBind> engines = new List<MonotouchBind>() 
                { 
                    new BindProperty(),
                    new BindMethod(),
                };
                return engines;
            }
        }


        public BindEnum()
            : base()
        {
            regexStart = new System.Text.RegularExpressions.Regex(patternStart);
            regexEnd = new System.Text.RegularExpressions.Regex(patternEnd);
            enumValues = new List<string>();
            EndString = ";";
        }

        public override bool CanParse(string code)
        {
            return regexStart.IsMatch(code);
        }

        public override int ParseSelfStart(string code)
        {
            this.ParseFiniseStatus = ParseStatus.Processing;
            return code.Length;
        }
        public override int ParseSelfBody(string code)
        {
            if (code.TrimEnd().EndsWith(","))
            {
                enumValues.Add(stringCache+code);
                stringCache = "";
            }
            else
            {
                stringCache += code;
            }
            return code.Length;
        }
        public override int ParseSelfEnd(string code)
        {

            if (stringCache.Trim().Length > 0)
            {
                enumValues.Add(stringCache);
                stringCache = "";
            }

            System.Text.RegularExpressions.Match match = regexEnd.Match(code);
            enumName = match.Groups["enumName"].Value;

            this.ParseFiniseStatus = ParseStatus.Finished;
            return match.Length;
        }

        public override string GenerateCSharp()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("public enum {0} {{ {1}", this.enumName,Environment.NewLine);
            foreach (var v in enumValues)
            {
                sb.Append("\t");
                sb.AppendLine(v.Trim());
            }
            sb.AppendLine("}");
            return sb.ToString();
        }
    }
}
